﻿using System.Collections.Generic;
using System.IO;
using Baidu.Aip.Face;
using UnityEngine;
using UnityEngine.UI;

public class TestFaceDetector : MonoBehaviour
{
    public RawImage faceImage;
    public Texture2D FaceTexture2D;

    private Face client;
    private byte[] image;
    private Dictionary<string , object> options;

    private void Awake()
    {
        System.Net.ServicePointManager.ServerCertificateValidationCallback +=
            delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                System.Security.Cryptography.X509Certificates.X509Chain chain,
                System.Net.Security.SslPolicyErrors sslPolicyErrors)
            {
                return true;
            };
        client = new Face("a7EY1wb5xIZ6csrH7xngGsiO", "91gcDeLgs4C7tG1dKOCPcH7dKUbFqqPi ");
        image = File.ReadAllBytes(Application.dataPath + "/shi4.jpg");
        options = new Dictionary<string, object>()
        {
            {"face_fields", "beauty,age,gender,landmark" }
        };
    }

    void Start () 
	{
		StartDetector();
	}

    //人脸特征点检测
    private void StartDetector()
    {
        var result = client.FaceDetect(image, options);
        Debug.Log(result.ToString());

        // 根据返回的landmark描绘特征点
        var landmarks = result["result"][0]["landmark72"];
   
        foreach (var lm in landmarks)
        {
            var x = int.Parse(lm["x"].ToString());
            var y = FaceTexture2D.height - int.Parse(lm["y"].ToString());

            for (int i = x - 1; i <= x + 1; i++)
            {
                for (int j = y - 1; j <= y + 1; j++)
                {
                    FaceTexture2D.SetPixel(i, j, Color.red);
                }
            }
        }
        FaceTexture2D.Apply();
        faceImage.texture = FaceTexture2D;



    }
}
